//
//  ZCOAuthViewController.swift
//  weibo
//
//  Created by Ning Xie on 16/8/10.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD

class ZCOAuthViewController: UIViewController {

    
    private lazy var webView:UIWebView = UIWebView()
    
    
    
    override func loadView() {
        
        view = webView
        webView.opaque = false
        webView.delegate = self
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupNavItem()
        requestOAuth()
    }
    
    private func setupNavItem(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(ZCOAuthViewController.cancelAction))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(ZCOAuthViewController.autoFillAction))
    }
    
    //MARK: 取消按钮的点击事件
    @objc private func cancelAction(){
        dismissViewControllerAnimated(true, completion: nil)
        SVProgressHUD.dismiss()
    }
    
    //MARK:自动填充按钮的点击事件
    @objc private func autoFillAction(){
        webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = 'chargezhang1988@126.com';document.getElementById('passwd').value = 'zhangchong'")
    }
    
    //MARK:加载第三方登录页面
    private func requestOAuth(){
        webView.loadRequest(ZCNetworkTools.sharedNetworkTools.requestOAuthLogin())
    }
        
}

//MARK: UIWebView的代理方法
extension ZCOAuthViewController :UIWebViewDelegate{
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
//        print(request.URL?.absoluteString)
        
        guard let url = request.URL else{
            return false
        }
        if !url.absoluteString.hasPrefix("http://www.itcast.cn/") {
            return true
        }
        
        if let query = url.query where query.hasPrefix("code="){

            let code = query.substringFromIndex("code=".endIndex)

            ZCUserInfoViewModel.sharedUserInfo.requestAccessToken(code, callBack: { (isSuccess) in
                
                if isSuccess{
                    print("登录成功")
                    self.dismissViewControllerAnimated(false, completion: { 

                        NSNotificationCenter.defaultCenter().postNotificationName(exchangeRootVC, object: self)
                    })
                    
                }else{
                    print("登录失败")
                }
            })
        }
        
        return true
    }
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.showWithStatus("正在加载")
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
        
    }
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
    }
  
    
}